package com.dsunsoft.rtu.common.util;

import com.dsunsoft.rtu.common.constant.CommonConstants;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * JacksonUtils
 *
 * @author ygm
 */
public class JsonUtils {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        // 日期转化
        OBJECT_MAPPER.setTimeZone(TimeZone.getTimeZone(CommonConstants.GMT_8));
        OBJECT_MAPPER.setDateFormat(new SimpleDateFormat(CommonConstants.YYYY_MM_DD_HH_MM_SS));
        // 设置空如何序列化
        OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        // 忽略json中不存在的属性
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 允许出现单引号
        OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    }

    /**
     * 对象转为json字符串
     *
     * @param obj 对象
     * @return json
     * @throws JsonProcessingException e
     */
    public static <T> String toJson(T obj) throws JsonProcessingException {
        return OBJECT_MAPPER.writeValueAsString(obj);
    }

    /**
     * json字符串转为JsonNode
     *
     * @param json json
     * @return JsonNode
     * @throws JsonProcessingException ex
     */
    public static JsonNode toJsonNode(String json) throws JsonProcessingException {
        return OBJECT_MAPPER.readTree(json);
    }

    /**
     * json字符串转为对象
     *
     * @param json json字符串
     * @param type class 类型
     * @return 对象
     * @throws JsonProcessingException ex
     */
    public static <T> T parseObject(String json, Class<T> type) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(json, type);
    }

    /**
     * json字符串转为Map
     *
     * @param json json字符串
     * @return map
     * @throws JsonProcessingException ex
     */
    @SuppressWarnings("rawtypes")
    public static Map parseMap(String json) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(json, Map.class);
    }

    /**
     * json字符串转为List
     *
     * @param json json字符串
     * @return list
     * @throws JsonProcessingException ex
     */
    public static <T> List<T> parseList(String json, Class<T> type) throws JsonProcessingException {
        JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class, type);
        return OBJECT_MAPPER.readValue(json, javaType);
    }
}
